package com.yanqu.road.server.manger.activity.taobao;

import com.yanqu.road.dao.impl.taobao.TaoBaoItemConfigDaoImpl;
import com.yanqu.road.dao.impl.taobao.TaoBaoLabelConfigDaoImpl;
import com.yanqu.road.dao.impl.taobao.TaoBaoPriceConfigDaoImpl;
import com.yanqu.road.dao.impl.taobao.TaoBaoPriceStatusConfigDaoImpl;
import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.taobao.TaoBaoModule;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;
import taobao.TaoBaoItem;
import taobao.TaoBaoLabel;
import taobao.config.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TaoBaoMgr extends TempMgr {

    private static TaoBaoConfig taoBaoConfig;

    private static Map<Integer, TaoBaoItemConfig> taoBaoItemConfigMap;

    private static Map<Integer, TaoBaoLabelConfig> taoBaoLabelConfigMap;

    private static Map<Integer, TaoBaoPriceConfig> taoBaoPriceConfigMap;

    private static Map<Integer, TaoBaoPriceStatusConfig> taoBaoPriceStatusConfigMap;

    private static RandomHelper randomHelper = new RandomHelper();

    private static long nextNotifyTime;

    public static int getLabelEffect(int id) {
        TaoBaoLabelConfig config = taoBaoLabelConfigMap.get(id);
        String[] split = config.getEffect().split(";");
        int min = Integer.parseInt(split[0]);
        int max = Integer.parseInt(split[1]);
        int next = randomHelper.next(min, max);
        return next;
    }

    public static TaoBaoConfig getTaoBaoConfig() {
        return taoBaoConfig;
    }

    public static Map<Integer, TaoBaoItemConfig> getTaoBaoItemConfigMap() {
        return taoBaoItemConfigMap;
    }

    public static Map<Integer, TaoBaoLabelConfig> getTaoBaoLabelConfigMap() {
        return taoBaoLabelConfigMap;
    }

    public static TaoBaoPriceStatusConfig getPriceStatusByFluctuation(int fluctuation) {
        for (TaoBaoPriceStatusConfig config : taoBaoPriceStatusConfigMap.values()) {
            if (fluctuation >= config.getMin() && fluctuation < config.getMax()) {
                return config;
            }
        }
        return null;
    }

    public static int getEarnPrice(TaoBaoPriceStatusConfig statusConfig) {
        int sellMin = statusConfig.getSellMin();
        int sellMax = statusConfig.getSellMax();
        int randomValue = randomHelper.next(sellMin, sellMax + 1);
        return randomValue;
    }

    public static int getBargainTimes() {
        return taoBaoConfig.getBargainTime();
    }

    public static boolean needReset(long resetTime) {
        if (taoBaoConfig == null) {
            return false;
        }
        resetTime = resetTime / 1000;
        String[] arr = taoBaoConfig.getRefreshTime().split(";");
        List<Integer> list = new ArrayList<>();
        //秒级
        int weekBeginTimestamp = DateHelper.getWeekBeginTimestamp();
        for (String s : arr) {
            list.add(weekBeginTimestamp + 60 * Integer.parseInt(s));
        }
        int now = DateHelper.getCurrentSecond();
        for (Integer time : list) {
            if (now >= time && resetTime < time) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    public static int getOpenActivityId() {
        List<ActivityInfo> openActivityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.TaoBao.getValue());
        if (openActivityInfoList.size() > 0) {
            return openActivityInfoList.get(0).getActivityId();
        }
        return 0;
    }

    public static boolean isActivityOpen() {
        int openActivityId = getOpenActivityId();
        return openActivityId > 0;
    }


    public static void reloadTaoBaoConfig() {
        List<ActivityInfo> openActivityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.TaoBao.getValue());
        if (openActivityInfoList.size() <= 0) {
            taoBaoConfig = null;
            taoBaoItemConfigMap = new HashMap<>();
            taoBaoLabelConfigMap = new HashMap<>();
            taoBaoPriceConfigMap = new HashMap<>();
            return;
        }
        int activityId = openActivityInfoList.get(0).getActivityId();
        Map<Integer, TaoBaoItemConfig> itemConfigMap = new TaoBaoItemConfigDaoImpl().getConfigMap(activityId);
        Map<Integer, TaoBaoLabelConfig> labelConfigMap = new TaoBaoLabelConfigDaoImpl().getConfigMap(activityId);
        Map<Integer, TaoBaoPriceConfig> priceConfigMap = new TaoBaoPriceConfigDaoImpl().getConfigMap(activityId);
        Map<Integer, TaoBaoPriceStatusConfig> statusConfigMap = new TaoBaoPriceStatusConfigDaoImpl().getConfigMap(activityId);
        List<Integer> activityIdList = new ArrayList<>();
        activityIdList.add(activityId);
        Map<String, ActivityConfig> activityConfigMap = ActivityBussiness.getActivityConfigMap(activityIdList).get(activityId);
        TaoBaoConfig tempConfig = TaoBaoConfig.parseConfig(activityConfigMap);
        if (taoBaoItemConfigMap == null || taoBaoItemConfigMap.size() == 0) {
            nextNotifyTime = 0;
        }else {
            for (TaoBaoItemConfig config : taoBaoItemConfigMap.values()) {
                if (config.getActivityId() != activityId) {
                    nextNotifyTime = 0;
                }
            }
        }
        taoBaoLabelConfigMap = labelConfigMap;
        taoBaoItemConfigMap = itemConfigMap;
        taoBaoConfig = tempConfig;
        taoBaoPriceConfigMap = priceConfigMap;
        taoBaoPriceStatusConfigMap = statusConfigMap;
        for (GamePlayer player : GamePlayerMgr.getAllOnlinePlayer()) {
            player.getModule(TaoBaoModule.class).init();
        }
    }

    /**
     * 随机事件
     */
    public static TaoBaoItem randomTaoBaoItem(int vipLv, boolean firstItem) {
        // 先随价格
        TaoBaoPriceConfig priceConfig = randomPriceConfig(vipLv);
        int itemId = priceConfig.getItemId();
        TaoBaoItemConfig itemConfig = taoBaoItemConfigMap.get(itemId);
        List<TaoBaoLabel> labelList = randomLabel(itemConfig,firstItem);
        TaoBaoItem taoBaoItem = new TaoBaoItem(itemConfig.getItemId(), priceConfig.getSellPrice(), labelList);
        return taoBaoItem;
    }

    public static TaoBaoPriceConfig randomPriceConfig(int vipLv) {
        List<TaoBaoPriceConfig> priceList = new ArrayList<>();
        List<Integer> weightList = new ArrayList<>();
        for (TaoBaoPriceConfig config : taoBaoPriceConfigMap.values()) {
            if (vipLv >= config.getVipLimit()) {
                priceList.add(config);
                weightList.add(config.getWeight());
            }
        }
        int index = RandomHelper.getRandomIndexByWeight(weightList);
        return priceList.get(index);
    }

    private static List<TaoBaoLabel> randomLabel(TaoBaoItemConfig itemConfig,boolean firstItem) {
        List<TaoBaoLabel> labelList = new ArrayList<>();
        int type = itemConfig.getType();
        //先根据物品类型随出所有标签
        List<TaoBaoLabelConfig> allLabel = findLabelConfigByType(type);

        //随出标签数量
        int labelSize = randomLabelSize(itemConfig);
        int lowSize = randomLowSize();
        int upSize = labelSize - lowSize;
        Map<Integer, Integer> faceNumMap = itemConfig.getFaceNumMap();
        while (allLabel.size() > 0) {
            TaoBaoLabelConfig config = xasdada(allLabel);
            allLabel.remove(config);
            if (config.getType() == 1 && upSize > 0) {
                List<Integer> faceList = config.getFaceList();
                List<Integer> temp = new ArrayList<>();
                for (Integer faceId : faceList) {
                    if (faceNumMap.getOrDefault(faceId, 0) > 0) {
                        temp.add(faceId);
                    }
                }
                int next = randomHelper.next(0, temp.size());
                Integer faceId = temp.get(next);
                TaoBaoLabelPositionConfig position = findPosition(itemConfig, labelList, faceId);
                labelList.add(new TaoBaoLabel(config.getTagId(), faceId, position.getX(), position.getY()));
                faceNumMap.put(faceId, faceNumMap.get(faceId) - 1);
                upSize--;
            } else if (config.getType() == 2 && lowSize > 0) {
                List<Integer> faceList = config.getFaceList();
                List<Integer> temp = new ArrayList<>();
                for (Integer faceId : faceList) {
                    if (faceNumMap.getOrDefault(faceId, 0) > 0) {
                        temp.add(faceId);
                    }
                }
                int next = randomHelper.next(0, temp.size());
                Integer faceId = temp.get(next);
                TaoBaoLabelPositionConfig position = findPosition(itemConfig, labelList, faceId);
                labelList.add(new TaoBaoLabel(config.getTagId(), faceId, position.getX(), position.getY()));
                faceNumMap.put(faceId, faceNumMap.get(faceId) - 1);
                lowSize--;
            }
        }
        return labelList;
    }


    private static TaoBaoLabelPositionConfig findPosition(TaoBaoItemConfig itemConfig, List<TaoBaoLabel> labelList, Integer faceId) {
        List<TaoBaoLabelPositionConfig> list = itemConfig.getPositionsByFaceId(faceId);
        for (TaoBaoLabel label : labelList) {
            if (label.getSurface() == faceId) {
                TaoBaoLabelPositionConfig hasConfig = null;
                for (TaoBaoLabelPositionConfig config : list) {
                    if (config.getX() == label.getX() && config.getY() == label.getY()) {
                        hasConfig = config;
                        break;
                    }
                }
                if (hasConfig != null) {
                    list.remove(hasConfig);
                }
            }
        }
        int next = randomHelper.next(0, list.size());
        TaoBaoLabelPositionConfig taoBaoLabelPositionConfig = list.get(next);
        return taoBaoLabelPositionConfig;
    }

    private static TaoBaoLabelConfig xasdada(List<TaoBaoLabelConfig> labelList) {
        List<Integer> weightList = new ArrayList<>();
        for (TaoBaoLabelConfig config : labelList) {
            weightList.add(config.getWeight());
        }
        int index = randomHelper.next(0, weightList.size());
        TaoBaoLabelConfig config = labelList.get(index);
        return config;
    }


    private static List<TaoBaoLabelConfig> findLabelConfigByType(int type) {
        List<TaoBaoLabelConfig> list = new ArrayList<>();
        for (TaoBaoLabelConfig config : taoBaoLabelConfigMap.values()) {
            List<Integer> list1 = StringUtils.stringToIntegerList(config.getLimitType(), ";");
            if (list1.contains(type)) {
                list.add(config);
            }
        }
        return list;
    }

    private static int randomLabelSize(TaoBaoItemConfig itemConfig) {
        int maxLabelSize = itemConfig.getMaxLabelSize();
        String[] arr = taoBaoConfig.getTagNumParam().split("\\|");
        List<Integer> numList = new ArrayList<>();
        List<Integer> weightList = new ArrayList<>();
        for (String s : arr) {
            String[] split = s.split(";");
            int num = Integer.parseInt(split[0]);
            int weight = Integer.parseInt(split[1]);
            numList.add(num);
            weightList.add(weight);
        }
        int index = RandomHelper.getRandomIndexByWeight(weightList);
        Integer num = numList.get(index);
        return Math.min(num, maxLabelSize);
    }

    private static int randomLowSize() {
        String[] arr = taoBaoConfig.getTagTypeParam().split("\\|");
        List<Integer> numList = new ArrayList<>();
        List<Integer> weightList = new ArrayList<>();
        for (String s : arr) {
            String[] split = s.split(";");
            int num = Integer.parseInt(split[0]);
            int weight = Integer.parseInt(split[1]);
            numList.add(num);
            weightList.add(weight);
        }
        int index = RandomHelper.getRandomIndexByWeight(weightList);
        Integer num = numList.get(index);
        return num;
    }

    public static void reset() {
        if (!isActivityOpen()) {
            return;
        }
        int now = DateHelper.getCurrentSecond();
        if (now < nextNotifyTime) {
            return;
        }
        for (GamePlayer player : GamePlayerMgr.getAllOnlinePlayer()) {
            player.getModule(TaoBaoModule.class).notifyReset();
        }
        String[] arr = taoBaoConfig.getRefreshTime().split(";");
        List<Integer> list = new ArrayList<>();
        //秒级
        int weekBeginTimestamp = DateHelper.getWeekBeginTimestamp();
        for (String s : arr) {
            list.add(weekBeginTimestamp + 60 * Integer.parseInt(s));
        }
        boolean changeNextTime = false;
        for (Integer time : list) {
            if (time > nextNotifyTime) {
                nextNotifyTime = time;
                changeNextTime = true;
                break;
            }
        }

        //如果遍历完没变
        int i = 1;
        while (!changeNextTime) {
            long addTime = DateHelper.WEEK_SECONDS * i;
            for (Integer time : list) {
                if (time + addTime > nextNotifyTime) {
                    nextNotifyTime = time + addTime;
                    changeNextTime = true;
                    break;
                }
            }
            i++;
        }
    }

}
